package com.ITXu.reggie.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ITXu.reggie.commom.R;
import com.ITXu.reggie.entity.User;
import com.ITXu.reggie.service.UserService;
import com.ITXu.reggie.utils.SMSUtils;
import com.ITXu.reggie.utils.ValidateCodeUtils;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@PostMapping("/sendMsg")
	public R<String> sendMsg(HttpServletRequest request, @RequestBody User user) {
		//获取手机号
		String phone = user.getPhone();
		if (org.apache.commons.lang.StringUtils.isNotEmpty(phone)) {
			//生产随机的四位验证码
			String code = ValidateCodeUtils.generateValidateCode(4).toString();
			log.info(code);
			//调用阿里云提供的短信服务API发送短信到对应手机号
			//SMSUtils.sendMessage("瑞吉外卖", code, phone, code);
			//将生产的验证码保存到session
			request.getSession().setAttribute(phone, code);
			return R.success("手机验证码发送成功");
		}
		return R.error("手机发送验证码失败");
	}
	
	@PostMapping("/login")
	public R<User> login(@RequestBody Map user, HttpServletRequest request){
		//获取手机号
		String phone = user.get("phone").toString();
		//获取验证码
		String code = user.get("code").toString();
		//从session中获取保存的验证码
		Object codeInSession = request.getSession().getAttribute(phone);
		//比对验证码
		if (codeInSession != null && codeInSession.equals(code)) {
			//判断当前手机号是不是新用户(select)，如果是自动完成注册（insert）
			LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(User::getPhone, phone);
			User currentUser = userService.getOne(queryWrapper);
			if (currentUser == null) {
				currentUser = new User();
				currentUser.setPhone(phone);
				currentUser.setStatus(1);
				userService.save(currentUser);
			}
			request.getSession().setAttribute("user", currentUser.getId());
			//log.info(currentUser.getId().toString());
			return R.success(currentUser);
		}
		
		return R.error("验证码错误，登录失败");
	}
	
}
